/* istanbul ignore next */
export const on = (element, event, handler) => {
  if (element && event && handler) {
    element.addEventListener(event, handler, false);
  }
};

/* istanbul ignore next */
export const off = (element, event, handler) => {
  if (element && event) {
    element.removeEventListener(event, handler, false);
  }
};

/* istanbul ignore next */
export const once = function once(el, event, fn) {
  const listener = (...args) => {
    if (fn) {
      fn.apply(this, args);
    }
    off(el, event, listener);
  };
  on(el, event, listener);
};

export const isElementInViewport = (el, { bottomOffset = 0 }) => {
  if (!el) {
    return false;
  }

  const rect = el.getBoundingClientRect();

  return (
    rect.bottom >= 0 &&
    rect.left >= 0 &&
    rect.top + bottomOffset <= (window.innerHeight || document.documentElement.clientHeight) &&
    rect.right <= (window.innerWidth || document.documentElement.clientWidth)
  );
};

export function getRect(el) {
  if (!el) {
    return {
      top: 0,
      left: 0,
      width: 0,
      height: 0,
    };
  }

  const rect = el.getBoundingClientRect();

  return {
    top: rect.top,
    left: rect.left,
    width: rect.width,
    height: rect.height,
  };
}

export function pxToRem(d, rootValue = 75) {
  let val = (parseFloat(d) / rootValue).toFixed(6);
  if (typeof d === 'string' && d.match(/px$/)) {
    val += 'rem';
  }
  return val;
}

export function hasClass(el, className) {
  const reg = new RegExp('(^|\\s)' + className + '(\\s|$)');
  return reg.test(el.className);
}

export function addClass(el, className) {
  if (hasClass(el, className)) {
    return;
  }

  const newClass = el.className.split(' ');
  newClass.push(className);
  el.className = newClass.join(' ');
}

export function removeClass(el, className) {
  if (!hasClass(el, className)) {
    return;
  }

  const reg = new RegExp('(^|\\s)' + className + '(\\s|$)', 'g');
  el.className = el.className.replace(reg, ' ');
}

export function getData(el, name, val) {
  const prefix = 'data-';
  if (val) {
    return el.setAttribute(prefix + name, val);
  }
  return el.getAttribute(prefix + name);
}
